using System;
using AesEverywhere;
using UnityEngine;
using UnityEngine.UI;

public class Redeem : MonoBehaviour
{
	[Serializable]
	public class RedeemData
	{
		public string code;

		public int add_gold;

		public int add_ads_free;

		public string token;
	}

	public GameObject panelView;

	public GameObject inputView;

	public GameObject loadingView;

	public GameObject resultView;

	public InputField inputField;

	public Text resultText;

	public AudioSource audioSource;

	public AudioClip successAudio;

	public AudioClip failAudio;

	private void Start()
	{
		Close();
	}

	public void Open()
	{
		inputField.text = null;
		resultView.SetActive(value: false);
		loadingView.SetActive(value: false);
		inputView.SetActive(value: true);
		panelView.SetActive(value: true);
	}

	public void Close()
	{
		panelView.SetActive(value: false);
	}

	public void RequestGift()
	{
		if (string.IsNullOrEmpty(inputField.text))
		{
			inputField.placeholder.color = Color.red;
			audioSource.PlayOneShot(failAudio);
		}
		else
		{
			loadingView.SetActive(value: true);
			StartCoroutine(Api.Get("/api.php?action=Redeem&code=" + inputField.text, HandleResult));
		}
	}

	private void HandleResult(string json)
	{
		RedeemData redeemData = JsonUtility.FromJson<RedeemData>(json);
		resultText.text = "Invaild code.";
		if (!string.IsNullOrEmpty(redeemData.token))
		{
			if (new AES256().Decrypt(redeemData.token, Config.encryptionKey) == inputField.text)
			{
				resultText.text = "";
				if (redeemData.add_ads_free > 0)
				{
					DO.Player.adFree = true;
					resultText.text += "+ Ads free & super reward forever";
				}
				if (redeemData.add_gold > 0)
				{
					DO.Player.gold += redeemData.add_gold;
					Text text = resultText;
					text.text = text.text + "\n+ " + redeemData.add_gold + " Gold";
				}
				SaveLoad.SaveString("Player", JsonUtility.ToJson(DO.Player));
				audioSource.PlayOneShot(successAudio);
			}
			else
			{
				audioSource.PlayOneShot(failAudio);
			}
		}
		else
		{
			audioSource.PlayOneShot(failAudio);
		}
		resultView.SetActive(value: true);
	}

	private void Update()
	{
	}
}
